package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.CustomerReturnListDao;
import com.atguigu.jxc.dao.CustomerReturnListGoodsDao;
import com.atguigu.jxc.dao.GoodsDao;
import com.atguigu.jxc.entity.*;
import com.atguigu.jxc.service.CustomerReturnListService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 * @author WZhaokang
 * @date 2020/12/30 2:12
 */
@Service
public class CustomerReturnListServiceImpl implements CustomerReturnListService {

    @Autowired
    private CustomerReturnListDao customerReturnListDao;
    @Autowired
    private CustomerReturnListGoodsDao customerReturnListGoodsDao;
    @Autowired
    private GoodsDao goodsDao;

    @Override
    public void save(CustomerReturnList customerReturnList, String customerReturnListGoodsStr, HttpSession session) {
        User user = (User) session.getAttribute("currentUser");
        customerReturnList.setUserId(user.getUserId());
        customerReturnListDao.save(customerReturnList);

        CustomerReturnListGoods[] customerReturnListGoods = new Gson().fromJson(customerReturnListGoodsStr, CustomerReturnListGoods[].class);
        List<CustomerReturnListGoods> customerReturnListGoodsList = Arrays.asList(customerReturnListGoods);
        for (CustomerReturnListGoods returnListGoods : customerReturnListGoodsList) {
            Integer customerReturnListId = customerReturnList.getCustomerReturnListId();
            returnListGoods.setCustomerReturnListId(customerReturnListId);
            Integer goodsId = returnListGoods.getGoodsId();
            Goods goods = goodsDao.findByGoodsId(goodsId);
            returnListGoods.setGoodsNum(goods.getInventoryQuantity() - returnListGoods.getGoodsNum());
            customerReturnListGoodsDao.save(returnListGoods);
        }
    }

    @Override
    public List<CustomerReturnList> list(String returnNumber, Integer customerId, Integer state, String sTime, String eTime) {
        return customerReturnListDao.list(returnNumber,customerId,state,sTime,eTime);
    }

    @Override
    public void delete(Integer customerReturnListId) {
        customerReturnListGoodsDao.delete(customerReturnListId);
        customerReturnListDao.delete(customerReturnListId);
    }

    @Override
    public List<PurchaseVO2> count(String sTime, String eTime, Integer goodsTypeId, String codeOrName) {
        return customerReturnListDao.count(sTime,eTime,goodsTypeId,codeOrName);
    }
}
